# 用户信息文件
import hashlib
import random
import time
from datetime import datetime

from django.core.paginator import Paginator
from django.db.models import Q
from django.http import HttpResponse
from django.shortcuts import render

# Create your views here.
from pet_admin.models import Users


def find(request, pageIndex=1):
    """
        查询全部用户信息视图
    """
    userObject = Users.objects  # 实例化User对象
    users = userObject.filter(user_status__lt=9).order_by('user_id')  # 过滤出来状态小于9的数据并升序排序
    searchKey = []
    # 获取并判断搜索条件
    key = request.GET.get("searchKey", None)  # 获取表单提交数据
    if key:
        users = users.filter(Q(user_id__contains=key) | Q(user_name__contains=key))
        searchKey.append("searchKey=" + key)

    # 分页处理
    pageIndex = int(pageIndex)
    page = Paginator(users, 10)  # 每页多少条
    maxPage = page.num_pages  # 获取最大页数
    # 处理页码越界
    if pageIndex > maxPage:
        pageIndex = maxPage
    if pageIndex < 1:
        pageIndex = 1
    pageUsers = page.page(pageIndex)  # 获取当前页数据
    pages = page.page_range  # 获取页码列表信息
    context = {"users": pageUsers, "pages": pages, "pageIndex": pageIndex, "maxPage": maxPage,
               "searchKey": searchKey}

    return render(request, 'pet_admin/user_manage/index.html', context)


def add(request):
    """
        添加用户信息视图
    """
    return render(request, "pet_admin/user_manage/add.html")


def insert(request):
    """
        执行添加程序方法
    """
    try:
        user = Users()
        user.user_account = request.POST["user_account"]
        # 密码md5处理
        md5Pw = hashlib.md5()
        randomNum = random.randint(100000, 999999)
        s = request.POST["user_password"] + str(randomNum)
        md5Pw.update(s.encode('utf-8'))
        user.user_password_hash = md5Pw.hexdigest()
        user.user_password_salt = randomNum

        user.user_name = request.POST["user_name"]
        myfile = request.FILES.get('user_path', None)
        if not myfile:
            return HttpResponse("没有上传头像")
        user_path = str(time.time()) + "." + myfile.name.split('.').pop()
        destination = open("./static/uploads/user_path/"+user_path, "wb+")
        for chunk in myfile.chunks():
            destination.write(chunk)
        destination.close()
        user.user_path = user_path
        # user.user_type = request.POST["user_type"]  # 用户类型：0.店主、1.代理、7.VIP、8.正常用户、9.黑名单
        # user.user_path = None  # 用户头像地址
        user.user_createtime = datetime.now().strftime("%Y-%m-%d %H:%M:%S")  # 用户创建时间
        user.user_updatetime = datetime.now().strftime("%Y-%m-%d %H:%M:%S")  # 用户修改时间
        user.user_sex = request.POST["user_sex"]  # 用户性别，0.女、1.男
        user.user_age = request.POST["user_sex"]  # 用户年龄
        user.user_remark = request.POST["user_sex"]  # 备注
        user.save()
        context = {"info": "添加成功"}

    except Exception as err:
        print(err)
        context = {"info": "添加失败"}

    return render(request, "pet_admin/info.html", context)


def edit(request, user_id):
    """
        修改用户信息视图
    """
    try:
        user = Users.objects.get(user_id=user_id)
        context = {"user": user}

        return render(request, "pet_admin/user_manage/edit.html", context)
    except Exception as err:
        print(err)
        context = {"info": "没有找到要修改的信息"}
        return render(request, "pet_admin/info.html", context)


def update(request, user_id):
    """
        执行修改程序的方法
    """
    try:
        user = Users.objects.get(user_id=user_id)
        user.user_name = request.POST["user_name"]
        # user.user_path = None  # 用户头像地址
        user.user_updatetime = datetime.now().strftime("%Y-%m-%d %H:%M:%S")  # 用户修改时间
        user.user_sex = request.POST["user_sex"]  # 用户性别，0.女、1.男
        user.user_age = request.POST["user_sex"]  # 用户年龄
        user.user_remark = request.POST["user_sex"]  # 备注
        user.save()
        context = {"info": "修改成功"}

    except Exception as err:
        print(err)
        context = {"info": "修改失败"}

    return render(request, "pet_admin/info.html", context)


def deluser(request, user_id):
    """
       执行删除程序的方法
    """
    try:
        user = Users.objects.get(user_id=user_id)
        user.user_status = 9
        user.user_updatetime = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        user.save()
        context = {"info": "删除成功"}

    except Exception as err:
        print(err)
        context = {"info": "删除失败"}

    return render(request, "pet_admin/info.html", context)


def upgrade_agent(request, user_id):
    """
       执行升级为代理的程序
    """
    try:
        user = Users.objects.get(user_id=user_id)
        user.user_type = 1
        user.user_updatetime = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        user.save()
        context = {"info": "升级成功"}

    except Exception as err:
        print(err)
        context = {"info": "升级失败"}

    return render(request, "pet_admin/info.html", context)


def doVip(request, user_id):
    """
       执行设置为Vip的程序
    """
    try:
        user = Users.objects.get(user_id=user_id)
        user.user_type = 2
        user.user_updatetime = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        user.save()
        context = {"info": "设置成功"}

    except Exception as err:
        print(err)
        context = {"info": "设置失败"}

    return render(request, "pet_admin/info.html", context)
